package com.smartphonedev.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.smartphonedev.sliding.Rorate3d;

public class Tab4Activity extends Activity
{
	private WebView mContainer;
	private String mainUrl;
	private boolean isInit;
	Activity activity;
	private ProgressBar progressBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab4);
		activity = this;
		mainUrl = "http://ketnoicontim.wapka.mobi/index.xhtml";
		initWebView(mainUrl);
	}

	public void initWebView(String url){ 
		Log.d("","initWebView():");    
		isInit = true;
		mContainer = (WebView) findViewById(R.id.webview);
		mContainer.getSettings().setJavaScriptEnabled(true);
		mContainer.loadUrl(url);
		mContainer.setWebViewClient(new TestWebViewClient());
		mContainer.setWebChromeClient(new TestWebChromeClient()); 
		mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		mContainer.setWebChromeClient(new WebChromeClient() 
		{
			@Override
			public void onProgressChanged(WebView view, int progress) 
			{               
				progressBar.setProgress(0);
				progressBar.setVisibility(View.VISIBLE);
				Tab4Activity.this.setProgress(progress * 1000);
				progressBar.incrementProgressBy(progress);
				if(progress == 100)
				{
					progressBar.setVisibility(View.GONE);
				}
			}
		});

	}    

	/**
	 * Setup a new 3D rotation on the container view.
	 *
	 * @param position the item that was clicked to show a picture, or -1 to show the list
	 * @param start the start angle at which the rotation must begin
	 * @param end the end angle of the rotation
	 */
	private void applyRotation(int position, float start, float end) {
		// Find the center of the container
		final float centerX = mContainer.getWidth() / 2.0f;
		final float centerY = mContainer.getHeight() / 2.0f;

		// Create a new 3D rotation with the supplied parameter
		// The animation listener is used to trigger the next animation
		final Rorate3d rotation =
				new Rorate3d(start, end, centerX, centerY, 310.0f, true);
		rotation.setDuration(500);
		rotation.setFillAfter(true);
		rotation.setInterpolator(new AccelerateInterpolator());
		rotation.setAnimationListener(new DisplayNextView(position));

		mContainer.startAnimation(rotation);
	}

	/**
	 * This class listens for the end of the first half of the animation.
	 * It then posts a new action that effectively swaps the views when the container
	 * is rotated 90 degrees and thus invisible.
	 */
	private final class DisplayNextView implements Animation.AnimationListener {
		private final int mPosition;

		private DisplayNextView(int position) {
			mPosition = position;
		}

		public void onAnimationStart(Animation animation) {
		}

		public void onAnimationEnd(Animation animation) {
			mContainer.post(new SwapViews(mPosition));
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}

	/**
	 * This class is responsible for swapping the views and start the second
	 * half of the animation.
	 */
	private final class SwapViews implements Runnable {
		private final int mPosition;

		public SwapViews(int position) {
			mPosition = position;
		}

		public void run() {
			final float centerX = mContainer.getWidth() / 2.0f;
			final float centerY = mContainer.getHeight() / 2.0f;
			Rorate3d rotation;

			if (mPosition > -1) {
				rotation = new Rorate3d(90, 0, centerX, centerY, 0.0f, false);
			} else {
				rotation = new Rorate3d(90, 0, centerX, centerY, 310.0f, true);
			}

			rotation.setDuration(500);
			rotation.setFillAfter(true);
			rotation.setInterpolator(new DecelerateInterpolator());

			mContainer.startAnimation(rotation);
		}
	}
	private class TestWebChromeClient extends WebChromeClient {
		public void onProgressChanged(WebView view, int progress) {
			activity.setProgress(progress * 100);
		} 
		@Override
		public boolean onJsAlert(WebView view, String url, String message,
				JsResult result){
			Log.e("Alert", ">> url :"+ url );
			Log.e("Alert", ">> msg :"+ message);
			result.confirm();
			return false;
		}
		@Override
		public boolean onJsConfirm(WebView view, String url, String message,
				JsResult result){
			Log.e("JsConfirm", ">> url :"+ url );
			Log.e("JsConfirm", ">> msg :"+ message);                
			return super.onJsConfirm(view, url, message, result);
		}
	}   
	private class TestWebViewClient extends WebViewClient {
		public void onReceivedError(WebView view, int errorCode, String description, String fallingUrl) {
			Toast.makeText(activity, "Ã«Â¡Å“Ã«â€�Â©Ì�ËœÂ¤Ã«Â¥Ëœ"+description, Toast.LENGTH_SHORT).show();
		}
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url){
			Log.d("HelloWebViewClient","#### UrlLoading()  :: "+url);
			if(url.endsWith(".apk"))
				downloadFile(url);
			else{
				view.clearView();
				view.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url){
			Log.d("HelloWebViewClient","#### onPageFinished()  ");
			//           applyRotation(1, 0, 90);
		}
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d("HelloWebViewClient","#### onPageStarted()  ");
			if(isInit){
				isInit = false;
			}else{
				applyRotation(1, 0, 90);
			}
			super.onPageStarted(view, url, favicon);
		}
	}
	private void downloadFile(String fileUrl){
		URL myFileUrl =null;          
		try {
			myFileUrl= new URL(fileUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			String mPath = "sdcard/download/downTest.apk";
			FileOutputStream fos;
			File f = new File(mPath);
			if ( f.createNewFile() ) {
				fos = new FileOutputStream(mPath);   
				int read;
				while ( (read =  is.read()) != -1) {
					fos.write(read);
				}
				fos.close();
				Toast.makeText(getApplicationContext(), "download complete", 0).show();
				// Ì�â€¢Ë†Ã«â€œÅ“Ã«Â¡Å“Ì�Â�Â´Ã«â€œÅ“ Ã­Å’Â¨Ã­â€šÂ¤Ì�Â§â‚¬ Ã«Â§Â¤Ã«â€¹Ë†Ì� â‚¬Ã«Â¥Â¼ Ã­â€ ÂµÃ­â€¢Â´ Ã«â€¹Â¤Ì�ÂšÂ´ Ã«Â°â€ºÌ�Â�â‚¬ apk Ã­Å’Å’Ì�Â�Â¼Ì�Â�â€ž Ì�Â²ËœÃ«Â¦Â¬Ã­â€¢ËœÃ«Â�â€žÃ«Â¡Â� Ã­â€¢Å“Ã«â€¹Â¤.
				Log.e("MEDIA_SHARED", ">> : "+Environment.MEDIA_SHARED);
				Log.e("StorageDirectory", ">> : "+Environment.getExternalStorageDirectory());
				Log.e("DownloadCacheDirectory", ">> : "+Environment.getDownloadCacheDirectory());
				File apkFile = new File(Environment.getExternalStorageDirectory()+ "/download/downTest.apk");
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType( Uri.fromFile(apkFile), "application/vnd.android.package-archive");
				startActivity(intent);
			}else{
				f.delete();
				Toast.makeText(getApplicationContext(), "already download file", 0).show();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void launchActivityOutApk() {

		Intent intent = new Intent("android.lgt.mofileviewer.intent.action.OPEN_FILE");

		intent.putExtra("app", "MBOFFICE");
		intent.putExtra("docid", "test.account%2Fmailbox%2F0001%2Fattach.conv%2F0000D7B29666");
		intent.putExtra("EMS_CMD", "mailattachview");
		intent.putExtra("Device-Info", "Eclipse");
		intent.putExtra("CompanyID", "company");
		intent.putExtra("DOMAIN", "lgcns.co.kr");
		intent.putExtra("serveraddr", "172.20.49.104");
		intent.putExtra("serverport", "8080");

		startActivity(intent);
	}       



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu2, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_exit2:
			Tab4Activity.this.finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder adb = new AlertDialog.Builder(this);
			adb.setTitle(R.string.confirm);
			adb.setIcon(R.drawable.exit);
			adb.setMessage(R.string.confirmexit);
			adb.setCancelable(false);
			adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Tab4Activity.this.finish();
				}
			});
			adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			adb.show();

			return true;
		}
		return false;
	}



}
